package com.casic.modules.gen.service.impl;


import com.casic.common.utils.Constant;
import com.casic.config.RedisCache;
import com.casic.modules.gen.dao.SysGeneratorDao;
import com.casic.modules.gen.entity.SysTableColumnEntity;
import com.casic.modules.gen.entity.SysTableInfoEntity;
import com.casic.modules.gen.service.SysGeneratorService;
import com.casic.modules.gen.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service("sysGeneratorService")
public class SysGeneratorServiceImpl implements SysGeneratorService {
	private static final Logger logger = LoggerFactory.getLogger(SysGeneratorServiceImpl.class);

	@Autowired
	private SysGeneratorDao sysGeneratorDao;

	@Value("${spring.datasource.driverClassName}")
	private String  driverClassName;

	@Override
	public List<SysTableInfoEntity> queryList(Map<String, Object> map) {
        if(Constant.ORACLE_DRIVERCLASSNAME.equals(driverClassName)){
			return sysGeneratorDao.queryListForOracle(map);
		}else if(Constant.MYSQL_DRIVERCLASSNAME.equals(driverClassName)){
			return sysGeneratorDao.queryList(map);
		}
		return null;
	}

	@Override
	public int queryTotal(Map<String, Object> map) {
		return sysGeneratorDao.queryTotal(map);
	}

	@Override
	public SysTableInfoEntity queryTable(String tableName) {
		if(Constant.ORACLE_DRIVERCLASSNAME.equals(driverClassName)){
			System.out.print(tableName+"++++++++++++++++++++++++");
			return sysGeneratorDao.queryTableForOracle(tableName);
		}else if(Constant.MYSQL_DRIVERCLASSNAME.equals(driverClassName)){
			return sysGeneratorDao.queryTable(tableName);
		}
		return null;
	}

	@Override
	public List<SysTableColumnEntity> queryColumns(String tableName) {
		if(Constant.ORACLE_DRIVERCLASSNAME.equals(driverClassName)){
			return sysGeneratorDao.queryColumnsForOracle(tableName);
		}else if(Constant.MYSQL_DRIVERCLASSNAME.equals(driverClassName)){
			return sysGeneratorDao.queryColumns(tableName);
		}
		return null;
	}

	@Override
	public byte[] generatorCode(String[] tableNames,String module,String author) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		
		for(String tableName : tableNames){
			//查询表信息
			SysTableInfoEntity table = queryTable(tableName);
			//查询列信息
			List<SysTableColumnEntity> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns, zip,module,author);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
